package com.example.monitoringsystem.realm;

import com.example.monitoringsystem.bean.User;
import com.example.monitoringsystem.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userServiceInterface;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //System.out.println("执行授权逻辑");
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //不授权先不写
        return info;
    }
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //System.out.println("执行认证逻辑"); // 编写shiro判断逻辑，判断用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; // 判断用户名
        User user = userServiceInterface.findUserByAccount(token.getUsername());
        if (user == null) { // 该用户不存在
            return null; // shiro底层会抛出UnKnowAccountException
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), ""); // 判断密码
    }

}
